import { useEffect, useState } from 'react';

import { Button, Form, Input, Radio, Upload, Cascader, UploadFile, Modal, InputNumber } from 'antd';
import { useModel, Access } from '@umijs/max'
import { OrgType, editOrg, getOrgInfo } from './services'
import { Card } from "@/components/Card"
import { useRequest } from 'ahooks';
import { enum2options } from '@/utils/enum2options';
import UserSelect from '@/components/UserSelect';
import { PlusOutlined } from '@ant-design/icons';
import { queryCityOptions2 } from '@/services/common';
import { SUCCESS_CODE } from '@/constants';
import { areaCode2cascaderValue } from '@/utils/common';

const OrgEditPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editOrg, {manual: true})
  const { data: orgInfo, runAsync: getData, mutate } = useRequest(getOrgInfo, {manual: true})
  const { data: cityOptions, loading: cityLoading } = useRequest(queryCityOptions2)
  const [editable, setEditable] = useState(true)
  const { closeCurrentTab } = useModel('global')
  const orgType = Form.useWatch('orgType', editForm)

  const onFinish = (formValues: any) => {
    const params: any = {
      id: orgInfo?.data.id,
      orgType: formValues.orgType,
      orgName: formValues.orgName,
      userId: formValues.admin.id,
      nickname: formValues.admin.name,
      telephone: formValues.admin.telephone,
      username: formValues.username,
      idCode: formValues.idCode,
      idImg: formValues.idImg?.[0]?.url,
      moneyRate: formValues.moneyRate / 100,
    }
    if (formValues.orgType === OrgType.个人) {
    } else {
      params.companyCode = formValues.companyCode
      params.username = formValues.username
      params.idCode = formValues.idCode
      params.companyPic = formValues.companyPic?.[0]?.url
      params.companyAddress = formValues.companyAddress
      params.province = formValues.city[0]
      params.city = formValues.city[1]
      params.district = formValues.city[2]
    }

    runAsync(params).then(() => {
      const event = new CustomEvent('refreshOrgList')
      window.dispatchEvent(event)
      closeCurrentTab('/station/org')
    })
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  }

  const onFileUpLoadChange = (file: UploadFile, field: string) => {
    const { status, response } = file
    if (status === 'done' && response) {
      const { code, data, text } = response
      if (code === SUCCESS_CODE) {
        editForm.setFieldsValue({
          [field]: [{status: 'done', url: data}]
        })
      } else {
        Modal.error({
          title: '错误',
          content: text === '上传文件过大' ? '文件体积超过 2M，请重新上传' : '图片上传失败，请重试',
        })
        editForm.setFieldsValue({
          [field]: []
        })
      }
    }
  }

  const onTypeChange = () => {
    editForm.resetFields()
    editForm.setFieldsValue({orgType: orgType === OrgType.个人 ? OrgType.企业 : OrgType.个人})
  }

  useEffect(() => {
    const { id, type } = props.params
    if (id) {
      getData({businessId: Number(id)})
      .then(res => {
        const { data } = res
        if (data.orgType === OrgType.个人) {
          editForm.setFieldsValue({
            orgType: data.orgType,
            username: data.username,
            idCode: data.idCode,
            admin: {
              id: data.userId,
              name: data.nickname,
              telephone: data.telephone,
            },
            idImg: data.idImg ? [{status: 'done', url: data.idImg}] : undefined,
            moneyRate: (data.moneyRate || 0) * 100,
          })
        } else {
          editForm.setFieldsValue({
            orgType: data.orgType,
            orgName: data.orgName,
            admin: {
              id: data.userId,
              name: data.nickname,
              telephone: data.telephone,
            },
            companyCode: data.companyCode,
            username: data.username,
            idCode: data.idCode,
            idImg: data.idImg ? [{status: 'done', url: data.idImg}] : undefined,
            companyPic: data.companyPic ? [{status: 'done', url: data.companyPic}] : undefined,
            companyAddress: data.companyAddress,
            city: areaCode2cascaderValue(data.district),
            moneyRate: (data.moneyRate || 0) * 100,
          })
        }
      })
    } else {
      editForm.resetFields()
      editForm.setFieldsValue({
        orgType: OrgType.企业,
      })
      mutate(undefined)
    }
    setEditable(type === 'edit')
  }, [props.params.id, props.params.type])

  return (
    <div className='container'>
      <Card>
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish} initialValues={{orgType: OrgType.企业}}>
          <Form.Item name='orgType' label='企业类型' rules={[{required: true, message: '请选择企业类型'}]}>
            <Radio.Group options={enum2options(OrgType)} disabled={!editable || !!orgInfo?.data} onChange={onTypeChange} />
          </Form.Item>
          <Access accessible={orgType === OrgType.个人}>
            <Form.Item name='username' label='姓名' rules={[{required: true, message: '请输入姓名'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item name='idCode' label='身份证号' rules={[{required: true, message: '请输入身份证号'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item
              name='idImg' label="身份证照片" rules={[{required: false, message: '请上传身份证照片'}]} 
              valuePropName="fileList" getValueFromEvent={normFile}
            >
              <Upload action="/app/user/fileUp" disabled={!editable}
                listType="picture-card" data={{type: 1}} 
                headers={{Authorization: localStorage.Authorization}}
                onChange={({file}) => onFileUpLoadChange(file, 'idImg')}
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>选择照片</div>
                </button>
              </Upload>
            </Form.Item>
          </Access>
          <Access accessible={orgType === OrgType.企业}>
            <Form.Item name='orgName' label='公司名称' rules={[{required: true, message: '请输入公司名称'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item name='username' label='法人姓名' rules={[{required: true, message: '请输入法人姓名'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item name='idCode' label='法人身份证号' rules={[{required: true, message: '请输入法人身份证号'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item
              name='idImg' label="法人身份证照片" rules={[{required: false, message: '请上传法人身份证照片'}]} 
              valuePropName="fileList" getValueFromEvent={normFile}
            >
              <Upload action="/app/user/fileUp" disabled={!editable}
                listType="picture-card" data={{type: 1}} 
                headers={{Authorization: localStorage.Authorization}}
                onChange={({file}) => onFileUpLoadChange(file, 'idImg')}
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>选择照片</div>
                </button>
              </Upload>
            </Form.Item>
            <Form.Item name='companyCode' label='公司税号' rules={[{required: true, message: '请输入公司税号'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item name='city' label='公司所在城市' rules={[{required: true, message: '请选择公司所在城市'}]}>
              <Cascader placeholder='请选择' options={cityOptions?.data} loading={cityLoading} style={{width: 320}} />
            </Form.Item>
            <Form.Item name='companyAddress' label='公司地址' rules={[{required: true, message: '请输入公司地址'}]}>
              <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
            </Form.Item>
            <Form.Item
              name='companyPic' label="营业执照" rules={[{required: false, message: '请上传营业执照'}]} 
              valuePropName="fileList" getValueFromEvent={normFile}
            >
              <Upload action="/app/user/fileUp" disabled={!editable}
                listType="picture-card" data={{type: 1}} 
                headers={{Authorization: localStorage.Authorization}}
                onChange={({file}) => onFileUpLoadChange(file, 'companyPic')}
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>选择照片</div>
                </button>
              </Upload>
            </Form.Item>
          </Access>
          <Form.Item name='moneyRate' label='分成比例' rules={[{required: true, message: '请输入分成比例'}]}>
            <InputNumber placeholder='0~100' style={{width: 320}} disabled={!editable} precision={0} min={0} max={100} />
          </Form.Item>
          <Form.Item name='admin' label='管理员' rules={[{required: true, message: '请选择管理员'}]}>
            <UserSelect style={{width: 320}} disabled={!editable} extraParams={{orgOw: 2}} />
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default OrgEditPage;
